package sfms.util;

/**
 * Based on example from http://www.mkyong.com/java/how-to-copy-directory-in-java/
 */

import java.io.*;
 
public class DirectoryCopier
{   
    public static boolean copy(String src, String dest) {   
        File srcFolder = new File(src);
        File destFolder = new File(dest);
 
        // Make sure source exists.
        if (!srcFolder.exists()){
           return false;
        } else {
           try {
            copyFolder(srcFolder,destFolder);
           } catch(Exception e){
            return false;
           }
        }
 
        return true;
    }
 
    public static void copyFolder(File src, File dest) throws IOException {
 
        if(src.isDirectory()){
 
            // If directory does not exist, create it.
            if(!dest.exists()){
               dest.mkdir();
            }
 
            // List all the directory contents.
            String files[] = src.list();
 
            for (String file : files) {
               
                   // Construct the src and dest file structure
               File srcFile = new File(src, file);
               File destFile = new File(dest, file);
               
                   // Recursive copy.
               copyFolder(srcFile, destFile);
            }
 
        } else {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest); 

            byte[] buffer = new byte[1024];

            int length;
            
            // Copy the file content in bytes.
            while ((length = in.read(buffer)) > 0){
               out.write(buffer, 0, length);
            }

            in.close();
            out.close();
        }
    }
}